package com.jlnk.servicedemo.views;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.jlnk.servicedemo.R;
import com.jlnk.servicedemo.service.CustomService;
import com.jlnk.servicedemo.widget.CircleImageView;

public class MusicActivity extends AppCompatActivity implements View.OnClickListener {
   private Button mLast;
   private Button mPlay;
   private Button mNext;
   private CircleImageView mIvMusic;
   private TextView mTvSongTitle;
   private TextView mTvArtistName;
   private SeekBar mSeekBarProgress;
   private TextView mTvCurrentTime;
   private TextView mTvTotalTime;
   private CustomService mService;
   private ServiceConnection mConnection;
   private boolean mPlaying = false;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_music);
      initializeUI();
      mConnection = new MyServiceConnection();
      Intent intent = new Intent(this, CustomService.class);
      bindService(intent, mConnection, BIND_AUTO_CREATE);
   }

   private void initializeUI() {
      mLast = findViewById(R.id.btn_last);
      mPlay = findViewById(R.id.btn_play);
      mNext = findViewById(R.id.btn_next);
      mIvMusic = findViewById(R.id.iv_music);
      mTvSongTitle = findViewById(R.id.tv_song_title);
      mTvArtistName = findViewById(R.id.tv_artist_name);
      mSeekBarProgress = findViewById(R.id.seekBar_progress);
      mTvCurrentTime = findViewById(R.id.tv_current_time);
      mTvTotalTime = findViewById(R.id.tv_total_time);

      mLast.setOnClickListener(this);
      mPlay.setOnClickListener(this);
      mNext.setOnClickListener(this);
   }

   @Override
   public void onClick(View v) {
      if (mService == null) {
         Log.e("MusicActivity", "Service is not bound.");
         return;
      }
      int id = v.getId();
      if (id == R.id.btn_last) {
         mService.last();
      } else if (id == R.id.btn_next) {
         mService.next();
      } else if (id == R.id.btn_play) {
         togglePlayPause();
      }
   }

   private void togglePlayPause() {
      if (mPlaying) {
         mService.pause();
         mPlay.setText("Play");
         mPlaying = false;
      } else {
         mService.play();
         mPlay.setText("Pause");
         mPlaying = true;
      }
   }

   private class MyServiceConnection implements ServiceConnection {
      @Override
      public void onServiceConnected(ComponentName name, IBinder service) {
         mService = ((CustomService.MyBinder) service).getService();
         mService.setOnMusicPlayStateChangeListener(new CustomService.OnMusicPlayStateChangeListener() {
            @Override
            public void onPlayStart() {
               mPlaying = true;
               mPlay.setText("Pause");
               updateUI();
               startProgressUpdate();
            }

            @Override
            public void onPlayStop() {
               mPlaying = false;
               mPlay.setText("Play");
               updateUI();
            }

            @Override
            public void onPlayComplete() {
               mPlaying = false;
               mPlay.setText("Play");
               updateUI();
               startNextSong();
            }

            @Override
            public void onProgressUpdate(int currentPosition, int duration) {
               runOnUiThread(() -> {
                  mSeekBarProgress.setProgress(currentPosition);
                  mTvCurrentTime.setText(formatTime(currentPosition));
                  mTvTotalTime.setText(formatTime(duration));
               });
            }
         });
         updateUI();
      }

      @Override
      public void onServiceDisconnected(ComponentName name) {
         mService = null;
      }
   }

   private void updateUI() {
      if (mService != null) {
         String title = mService.getSongTitle();
         String artist = mService.getArtistName();
         int duration = mService.getDuration();
         int currentPosition = mService.getCurrentPosition();

         mTvSongTitle.setText(title);
         mTvArtistName.setText(artist);
         mSeekBarProgress.setMax(duration);
         mSeekBarProgress.setProgress(currentPosition);
         mTvCurrentTime.setText(formatTime(currentPosition));
         mTvTotalTime.setText(formatTime(duration));
      }
   }

   private void startProgressUpdate() {
      if (mService != null) {
         mService.startProgressUpdate();
      }
   }

   private void startNextSong() {
      if (mService != null) {
         mService.next();
      }
   }

   private String formatTime(int millis) {
      int seconds = millis / 1000;
      int minutes = seconds / 60;
      seconds = seconds % 60;
      return String.format("%02d:%02d", minutes, seconds);
   }
}